import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_taotaoshipin/common/theme/app_colors.dart';
import 'package:flutter_taotaoshipin/model/drama_banner_entity.dart';
import 'package:flutter_taotaoshipin/util/global.dart';
import 'package:flutter_taotaoshipin/util/image_utils.dart';
import 'package:flutter_taotaoshipin/widget/gaps.dart';
import 'package:flutter_taotaoshipin/widget/load_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_swiper_null_safety_flutter3/flutter_swiper_null_safety_flutter3.dart';
import 'package:get/get.dart';

import 'subscription_open_controller.dart';

class SubscriptionOpenPage extends StatefulWidget {
  const SubscriptionOpenPage({Key? key}) : super(key: key);

  @override
  State<SubscriptionOpenPage> createState() =>
      _SubscriptionOpenPageState();
}

class _SubscriptionOpenPageState extends State<SubscriptionOpenPage> {
  final controller = Get.find<SubscriptionOpenController>();
  final state = Get.find<SubscriptionOpenController>().state;

  @override
  void dispose() {
    Get.delete<SubscriptionOpenController>();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      child: Scaffold(
        backgroundColor: Colors.white,
        body: Stack(
          children: [
            GetBuilder<SubscriptionOpenController>(
              builder: (controller) {
                return state.goodsList.isEmpty
                    ? const Center(child: CircularProgressIndicator.adaptive())
                    : _content();
              },
            ),
            GetBuilder<SubscriptionOpenController>(
                id: 'show_back',
                builder: (controller) {
                  return Visibility(
                    visible: state.showBack,
                    child: Positioned(
                      top: 44,
                      right: 16,
                      child: IconButton(
                        onPressed: () {
                          Get.back();
                        },
                        icon: LoadAssetImage(
                          'subscription/open/close',
                          width: 24,
                        ),
                      ),
                    ),
                  );
                }),
          ],
        ),
      ),
      onWillPop: () async => controller.state.showBack,
    );
  }

  _content() {
    return CustomScrollView(
      slivers: [
        _buildHeader(),
        _buildGoodTop(),
        _buildPayButton(),
        _buildAgreement(),
        _buildDecsription(),
      ],
    );
  }

  _buildHeader() {
    return DecoratedSliver(
      decoration: BoxDecoration(
        image: DecorationImage(
          image:
              ImageUtils.getAssetImage('subscription/open/header'),
          fit: BoxFit.fitWidth,
          alignment: Alignment.topCenter,
        ),
      ),
      sliver: SliverToBoxAdapter(
        child: Column(
          children: [
            SizedBox(height: 56.w),
            LoadAssetImage(
              'subscription/open/title',
              height: 100,
            ),
            _buildBanner(),
            Container(
              width: double.infinity,
              height: 15,
              decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.vertical(top: Radius.circular(15)),
              ),
            ),
          ],
        ),
      ),
    );
  }

  _buildGoodTop() {
    return SliverToBoxAdapter(
      child: Padding(
        padding: const EdgeInsets.fromLTRB(17, 0, 17, 0),
        child: Stack(
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 10),
              child: GestureDetector(
                onTap: () {
                  controller.payButtonClicked();
                },
                child: AspectRatio(
                  aspectRatio: 342 / 115,
                  child: Container(
                    decoration: BoxDecoration(
                      image: DecorationImage(
                          image: ImageUtils.getAssetImage(
                              'subscription/top_item_bg')),
                    ),
                    child: Row(
                      children: [
                        SizedBox(width: 13),
                        Text.rich(
                          TextSpan(
                            text: '¥ ',
                            children: [
                              TextSpan(
                                text:
                                    '${MoneyUtil.changeYWithUnit(state.currGood!.amount!, MoneyUnit.NORMAL, format: MoneyFormat.END_INTEGER)}',
                                style: TextStyle(
                                  fontSize: 53,
                                  fontWeight: FontWeight.w900,
                                ),
                              ),
                            ],
                          ),
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 23,
                            fontWeight: FontWeight.w600,
                          ),
                        ),
                        SizedBox(width: 9),
                        Expanded(
                          child: Text(
                            '畅看短剧\n每人仅限一次优惠',
                            style: TextStyle(
                              color: Colors.white,
                              fontSize: 18,
                            ),
                          ),
                        ),
                        Container(
                          padding:
                              EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                          decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(8),
                          ),
                          child: Text(
                            '立即开通',
                            style: TextStyle(
                              color: Color(0xFF012078),
                              fontSize: 14,
                              fontWeight: FontWeight.w900,
                            ),
                          ),
                        ),
                        SizedBox(width: 16),
                      ],
                    ),
                  ),
                ),
              ),
            ),
            LoadAssetImage(
              'subscription/new_gift_tag',
              width: 77,
              height: 21,
            ),
          ],
        ),
      ),
    );
  }

  _buildPayButton() {
    return SliverToBoxAdapter(
      child: GetBuilder<SubscriptionOpenController>(
        builder: (controller) {
          return Padding(
            padding: const EdgeInsets.only(top: 24),
            child: GestureDetector(
              onTap: () {
                controller.payButtonClicked();
              },
              child: Container(
                width: double.infinity,
                height: 50,
                margin: EdgeInsets.symmetric(horizontal: 17),
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  gradient: LinearGradient(
                    colors: [
                      Color(0xFF7AB3FF),
                      Color(0xFF2760FF),
                    ],
                    begin: Alignment.topCenter,
                    end: Alignment.bottomCenter,
                  ),
                  boxShadow: [
                    BoxShadow(
                      color: Color(0x993972FF),
                      offset: Offset(0, 5),
                      blurRadius: 10,
                    ),
                  ],
                  borderRadius: BorderRadius.circular(10),
                ),
                child: Text(
                  '¥${MoneyUtil.changeYWithUnit(_hasSubscripted() ? state.currGood!.subAmount! : state.currGood!.amount!, MoneyUnit.NORMAL, format: MoneyFormat.END_INTEGER)}立即开通',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 18,
                    fontWeight: FontWeight.w900,
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }

  _buildAgreement() {
    return SliverToBoxAdapter(
      child: GetBuilder<SubscriptionOpenController>(
          id: 'agreement_button',
          builder: (controller) {
            return GestureDetector(
              onTap: () {
                controller.agreePrivacyBtnClicked();
              },
              child: Padding(
                padding: const EdgeInsets.only(top: 30, bottom: 20),
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    if (state.isAgreePrivacy)
                      LoadAssetImage('subscription/agree_sel',
                          width: 14)
                    else
                      LoadAssetImage('subscription/agree_normal',
                          width: 14),
                    SizedBox(width: 5),
                    RichText(
                      text: TextSpan(
                        text: "我同意",
                        style: TextStyle(
                            color: AppColors.text_gray,
                            fontSize: 12),
                        children: [
                          TextSpan(
                            text: "《会员用户协议》",
                            style:
                                TextStyle(color: AppColors.app_main),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                Global.openVipUserProtocol();
                              },
                          ),
                          TextSpan(text: '和'),
                          TextSpan(
                            text: "《自动续费服务规则》",
                            style:
                                TextStyle(color: AppColors.app_main),
                            recognizer: TapGestureRecognizer()
                              ..onTap = () {
                                Global.openAutoRenewPolicy();
                              },
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            );
          }),
    );
  }

  _buildDecsription() {
    return SliverToBoxAdapter(
      child: Container(
        alignment: Alignment.centerLeft,
        padding: EdgeInsets.fromLTRB(17, 0, 17, 17),
        child: Text(
          '''1、付款时向您的 Apple lD 账户收取费用；\n2、订阅到期或免费试用结束前 24 小时内，将按页面价格自动续订所选套餐时长；同一 ApplelD 仅能享有一次免费试用资格；\n3、如需取消自动续订需在当前订阅周期结束至少 24 小时以前在 iTunes Store 设置中关闭自动续订服务。''',
          style: TextStyle(
            color: AppColors.text_gray,
            fontSize: 10,
            letterSpacing: 0.5,
            height: 1.5,
          ),
        ),
      ),
    );
  }

  _buildBanner() {
    return GetBuilder<SubscriptionOpenController>(
        id: 'banner',
        builder: (controller) {
          if (controller.state.bannerList.isEmpty) {
            return Container();
          }

          var item = controller.state
              .bannerList[controller.state.currSel];
          return Column(
            children: [
              Container(
                width: double.infinity,
                height: 230.w,
                padding: EdgeInsets.fromLTRB(0, 15, 0, 0),
                child: Swiper(
                  itemCount: state.bannerList.length,
                  controller: controller.swiperController,
                  autoplay: true,
                  autoplayDelay: 5000,
                  viewportFraction: 0.44,
                  scale: 0.6,
                  loop: true,
                  itemBuilder: (context, index) {
                    return _buildBannerImage(
                        state.bannerList[index], index);
                  },
                  onIndexChanged: (index) {
                    controller.updateCurr(index);
                  },
                ),
              ),
              Gaps.vGap15,
              Text(
                item.dramaName!,
                style: TextStyle(
                  color: Colors.white,
                  fontWeight: FontWeight.bold,
                  fontSize: 18,
                ),
              ),
              Container(
                alignment: Alignment.centerLeft,
                padding: EdgeInsets.symmetric(horizontal: 17, vertical: 15),
                child: Text(
                  '剧集可能存在上下架变动，以上内容仅供参考。',
                  style: TextStyle(
                    color: Colors.white,
                    fontSize: 10,
                  ),
                ),
              ),
            ],
          );
        });
  }

  _buildBannerImage(DramaBannerEntity img, int idx) {
    return Container(
      decoration: BoxDecoration(
        border: state.currSel == idx
            ? Border.all(color: Colors.white, width: 2)
            : null,
        borderRadius: BorderRadius.circular(8),
      ),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(8),
        child: LoadImage(img.bannerImg ?? ''),
      ),
    );
  }

  bool _hasSubscripted() {
    bool isSubscripted = false;
    if (state.payConfigListEntity != null &&
        state.payConfigListEntity!.userSubTimes! > 0) {
      isSubscripted = true;
    }
    return isSubscripted;
  }
}
